package com.zlt.websocket;

import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.zlt.dto.MessageDTO;
import com.zlt.entity.ChatMessageDetail;
import com.zlt.service.ChatMessageService;
import com.zlt.service.UserService;
import com.zlt.service.impl.ChatMessageServiceImpl;
import com.zlt.service.impl.UserServiceImpl;
import com.zlt.util.JWTUtil;
import com.zlt.vo.MessageVO;

@ServerEndpoint("/ws/{token}")
public class MyWebSocket {
    //用户id——session
    private static final ConcurrentHashMap<String, Session> hashMap = new ConcurrentHashMap<>();

    private final ChatMessageService service = new ChatMessageServiceImpl();
    private final UserService userService = new UserServiceImpl();
    //用户id
    private String uid;
    //用户角色
    private int role;

    @OnOpen
    public void onOpen(@PathParam("token") String token, Session session) throws IOException {

        uid = MyJWTToUid(token);
        System.out.println("onOpen:token->" + uid + " session->" + session);
        role = userService.getRoleByUsername(JWTUtil.getUsername(token));
//        用户上线
        hashMap.put(uid, session);
    }

    @OnClose
    public void onClose(@PathParam("token") String token) throws IOException {
        System.out.println("onClose->" + token + " session->" + hashMap.get(MyJWTToUid(token)));
//        用户下线
        hashMap.remove(MyJWTToUid(token));
    }

//    @OnMessage
//    public void onMessage(String message) throws IOException, ParseException, SQLException {
//        System.out.println(message);
//
//        MessageDTO messageDTO = JSON.parseObject(message, MessageDTO.class);
//        char hasRead = '0';//未读
//        //查询目标是否在线
//        //在线发送，不在线就保存到数据库中
//        if (hashMap.containsKey(messageDTO.getTo())) {//在线
//            //将数据发送给目标机
//            //响应对象
//            MessageVO vo = new MessageVO();
//            String string = JSON.toJSONString(messageDTO.getContent());
//            vo.setMessage(string);
//            hashMap.get(messageDTO.getTo()).getAsyncRemote().sendText(string);
//            //发送 -变成已读
//            hasRead = '1';
//        }
//        //将数据存入数据库
//        //存入聊天信息主表
//        Integer mainId = service.addMain(uid, messageDTO.getTo());
//        ChatMessageDetail detail = new ChatMessageDetail();
//        detail.setMainId(mainId);
//        detail.setSendUser(uid);
//        detail.setReceiveUser(messageDTO.getTo());
//        detail.setContent(messageDTO.getContent());
//        detail.setHasRead(hasRead);
//        //存入聊天信息详细表
//        int addDetail = service.addDetail(detail);
//        System.out.println(addDetail);
//    }


    @OnMessage
    public void onMessage(String message) throws IOException, ParseException, SQLException {
        //获取传入的数据
        MessageDTO messageDTO = JSON.parseObject(message, MessageDTO.class);

        String to = userService.getUserUid( messageDTO.getTo() );
        System.out.println(to);
        char hasRead = '0';//未读
        //查询目标是否在线
        //在线发送，不在线就保存到数据库中
//        System.out.println(messageDTO.getTo());
        if (hashMap.containsKey(  to  ) ) {//在线
            //将数据发送给目标机
            //响应对象
            MessageVO messageVO = new MessageVO();
            messageVO.setMessage(messageDTO.getContent());
            String string = JSON.toJSONString(messageVO);

            hashMap.get( to ).getAsyncRemote().sendText(string);
            //发送 -变成已读
            hasRead = '1';
        }
        //将数据存入数据库
        //存入聊天信息主表
        Integer mainId = 0;
        if(role == 1){//求职者
//            mainId = service.addMainTable(uid, to, messageDTO.getCid(), messageDTO.getJid());
            mainId = service.getMainId(uid, to);
        }else if(role == 2){//招聘者
//            mainId = service.addMainTable(to, uid, messageDTO.getCid(), messageDTO.getJid());
            mainId = service.getMainId(to,uid);
        }
//        Integer mainId = service.addMain(username, messageDTO.getTo());
        ChatMessageDetail detail = new ChatMessageDetail();
        detail.setMainId(mainId);
//        String uid1 = userService.getUserUid(uid);
//        detail.setSendUser(uid1);
        detail.setSendUser(uid);
//        String uid2 = userService.getUserUid(messageDTO.getTo());
//        detail.setReceiveUser(uid2);
        detail.setReceiveUser(to);
        detail.setContent(messageDTO.getContent());
        detail.setHasRead(hasRead);
//        //存入聊天信息详细表
        int addDetail = service.addDetail(detail);
        System.out.println(addDetail);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("onERROR --> session->" + session + " error -> " + error);
    }

    /**
     * 查询用户的UUID
     *
     * @param token 携带的token
     * @return 用户id
     */
    private String MyJWTToUid(String token) {
//        System.out.println(JWTUtil.getUsername(token));
        return userService.getUserUid(JWTUtil.getUsername(token));
    }

}
